<?php

declare(strict_types=1);

namespace app\admin\controller;

use addons\Builder\facade\Builder;
use app\common\model\ProductCate;
use app\common\model\Merchant;
use think\facade\View;
use think\Response;
use think\response\Json;
use app\common\tool\Result;

class Product extends Base
{

    //主键，默认为id
    protected string $pk = 'id';

    //主模型
    protected string $model = '\app\common\model\Product';

    //关联模型
    protected array $hasOne = ['cate1', 'cate2', 'merchant'];

    protected string $validate = 'Product';

    protected array $tape = [
        ['field' => 'icon', 'title' => '图片', 'type' => 'icon'],
        ['field' => 'price', 'title' => '原价'],
        ['field' => 'vip_price', 'title' => '会员价'],
        ['field' => 'stock', 'title' => '库存', 'type' => 'stock']
    ];
    /**
     * 积分商城
     */
    public function integral()
    {
        $sech = [
            ['title', '输入商品名称/描述', 'input,Like'],
            ['title', '分类', 'selectGroup', self::getCate(1)]
        ];
        return $this->index(['shop_type', '=', 1], 1, $sech);
    }
    /**
     * 金币商城
     */
    public function gold()
    {
        $sech = [
            ['title', '输入商品名称/描述', 'input,Like'],
            ['title', '分类', 'selectGroup', self::getCate(2)],
            ['merchant_id', '所属商家', 'select', self::getMerchantList()]
        ];

        return $this->index(['shop_type', '=', 2], 2, $sech);
    }

    public function index($extra_map, $shop_type, $sech): string
    {
        //构建table
        $table = Builder::Table()
            ->autoStructure($this->model, $this->pk, 'barProductDemo,90');
        if ($shop_type == 2) {
            $table->autoSpliceColumns(6, ['title' => '所属商家'], "merchant", false)
                ->addTopButtons([
                    'batchAudit' => [
                        'title' => '批量审核', 'icon' => 'layui-icon-util',
                        'url'   => url('product/batch')->build(),
                        'event' => '_batchSubmit'
                    ],
                    'add' => [
                        'size' => '80%',
                        'url'   => url('product/add', ['shop_type' => $shop_type])->build(),
                        'event' => '_openNewPage'
                    ], 'deleteAll'

                ]);
        } else {
            $table->addTopButtons([
                'add' => [
                    'size' => '80%',
                    'url'   => url('product/add', ['shop_type' => $shop_type])->build(),
                    'event' => '_openNewPage'
                ], 'deleteAll'

            ]);
        }

        return $table->addRightButtons(['editProduct' => [
            'size' => '80%','title' => '编辑', 'unity_title' => '审核',
            'url'   => url('product/edit', ['shop_type' => $shop_type])->build(),
            'event' => '_openNewPage'
        ]])
            ->addSearch($sech)
            ->addExtraMap([$extra_map])
            ->fetch();
    }

    public static function getCate($shop_type): array
    {
        return \app\common\model\ProductCate::where('pid', $shop_type)->field('id,title')->with('child')->select()->toArray();
    }
    public function batch()
    {
        return Result::fastReturn($this->model::batch($this->request->param('ids'), $this->admin));
    }
    public function add($tpl = '')
    {
        $params = $this->request->get();
        // print_r($params);die;
        View::assign('cate', self::getCate($params['shop_type']));
        View::assign('tape', $this->tape);
        View::assign('merchant', self::getMerchant());
        View::assign('shop_type', $params['shop_type']);
        return parent::add('product/edit'); // TODO: Change the autogenerated stub
    }

    public function edit($id = '', $tpl = '', $info = '')
    {
        $params = $this->request->get();
        View::assign('cate', self::getCate($params['shop_type']));
        View::assign('tape', $this->tape);
        View::assign('shop_type', $params['shop_type']);
        View::assign('merchant', self::getMerchant());
        return parent::edit($id, 'product/edit', $info); // TODO: Change the autogenerated stub
    }

    public function save($param = [], $model = true): Json
    {
        $param = $this->request->post();
        if ($param['shop_type'] == 2) {
            $param['merchant_bl'] = $param['merchant_bl'] / 100;
            $param['tp_1'] = $param['tp_1'] / 100;
            $param['tp_2'] = $param['tp_2'] / 100;
            $param['service_1'] = $param['service_1'] / 100;
            $param['service_2'] = $param['service_2'] / 100;
            $param['service_3'] = $param['service_3'] / 100;
        }
        return parent::save($param, $model); // TODO: Change the autogenerated stub
    }

    /**
     * 原点 2021年7月27日14:46:29 公共删除方法
     */
    public function delete(): Response
    {
        try {
            $param = $this->request->post();
            return json($this->model::productDelete($param, $this->getLogsArguments($param)));
        } catch (\Exception $e) {
            return json(['code' => -1, 'msg' => $e->getMessage()]);
        }
    }
    /**
     * 获取商家
     */
    public static function getMerchant()
    {
        return Merchant::where('status', 2)->field("id,title")->order('id asc')->select();
    }

    public static function getMerchantList()
    {
        $data = [];
        $list = Merchant::where('status', 2)->field('id,title')->order('id asc')->select()->toArray();
        foreach ($list as &$v) {
            $data[$v['id']] = $v['title'];
        }
        return $data;
    }
}
